from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.TextArea import TextArea
from pyjamas.ui.TextBox import TextBox
from pyjamas.ui.Button import Button
from pyjamas.ui.HTML import HTML
from pyjamas.ui.Label import Label
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.ListBox import ListBox
from pyjamas import Window

from pyjamas.JSONService import JSONProxy

class Passwordle_Main_UI:
  def onModuleLoad(self):
    self.remote_service = JSONProxy("/json", ["get_password", "get_all_passwords", "save_passwords", "change_master_key"])

    # Get all the passwords from the server

    #passwords = self.remote_service.get_all_passwords(self)
    
    # New Password Area
    self.new_password_panel = HorizontalPanel()
    for item in ["Label", "Username", "Website", "Other", "Password"]:
      panel = VerticalPanel()
      label = HTML(item)
      value = TextBox()
      panel.add(label)
      panel.add(value)
      self.new_password_panel.add(panel)
      attr_text = item.lower()
      setattr(self, 'new_password_%s_panel' % attr_text, panel)
      setattr(self, 'new_password_%s_label' % attr_text, label)
      setattr(self, 'new_password_%s_value' % attr_text, value)
    self.new_password_submit_button = Button("Add", New_Password_Handler(self).onClick)
    self.new_password_panel.add(self.new_password_submit_button)
    info = r'This example demonstrates the calling of appengine upper(case) method with JSON-RPC from javascript (i.e. Python code compiled with pyjs to javascript).'
    panel = VerticalPanel()
    panel.add(self.new_password_panel)
    self.debug_panel = TextArea()
    self.debug_panel.setCharacterWidth(80)
    self.debug_panel.setVisibleLines(8)
    panel.add(self.debug_panel)
    RootPanel().add(panel)

  def debug(self, message):
    text = self.debug_panel.getText()
    text += '\n%s' % message
    self.debug_panel.setText(text)

class Handler:
  def __init__(self, ui):
    self.ui = ui

class New_Password_Handler(Handler):
  def onClick(self, sender):
    new_password_data = {"id":None,
            "label":self.ui.new_password_label_value.getText(),
            "username":self.ui.new_password_username_value.getText(),
            "password":self.ui.new_password_password_value.getText(),
            "website":self.ui.new_password_website_value.getText(),
            "other":self.ui.new_password_other_value.getText(),
            }
    result = self.ui.remote_service.save_passwords([new_password_data], self)
    if result < 0:
      pass

  def onRemoteResponse(self, response, request_info):
    pass

  def onRemoteError(self, code, message, request_info):
    self.ui.debug(message)

if __name__ == "__main__":
  Passwordle_Main_UI().onModuleLoad()

